/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    DIA Proteomics Analysis Subworkflow Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Configuration file for the dia_proteomics_analysis subworkflow that replicates
    the quantms DIA-NN workflow behavior using nf-core modules.

    This configuration sets up the ext.args for each DIA-NN module to match
    the default quantms behavior and parameters.
----------------------------------------------------------------------------------------
*/

process {

    // QUANTMSUTILS_GENERATECFG - Configuration generation
    withName: 'QUANTMSUTILS_DIANNCFG' {
        ext.args = ''
    }

    // DIANN_INSILICOLIBRARYGENERATION - In-silico library generation
    // What makes this "In-Silico Library Generation":
    //   - Input: FASTA file + enzyme/modification config (from meta.config)
    //   - Key flags: --fasta-search --predictor --gen-spec-lib --met-excision --rt-profiling
    //   - Output: *.predicted.speclib (predicted spectral library from sequences)
    //   - No MS data input required at this stage
    withName: 'DIANN_INSILICOLIBRARYGENERATION' {
        ext.args = {[
            meta.config ?: '',
            params.min_pr_mz ? "--min-pr-mz ${params.min_pr_mz}" : '',
            params.max_pr_mz ? "--max-pr-mz ${params.max_pr_mz}" : '',
            params.min_fr_mz ? "--min-fr-mz ${params.min_fr_mz}" : '',
            params.max_fr_mz ? "--max-fr-mz ${params.max_fr_mz}" : '',
            params.allowed_missed_cleavages != null ? "--missed-cleavages ${params.allowed_missed_cleavages}" : '',
            params.min_peptide_length ? "--min-pep-len ${params.min_peptide_length}" : '',
            params.max_peptide_length ? "--max-pep-len ${params.max_peptide_length}" : '',
            params.min_precursor_charge ? "--min-pr-charge ${params.min_precursor_charge}" : '',
            params.max_precursor_charge ? "--max-pr-charge ${params.max_precursor_charge}" : '',
            params.max_mods != null ? "--var-mods ${params.max_mods}" : '',
            params.diann_debug ? "--verbose ${params.diann_debug}" : '',
            "--fasta-search",
            "--predictor",
            "--gen-spec-lib",
            "--rt-profiling",
            "--met-excision"
        ].findAll { it != '' }.join(' ').trim()}
    }

    // DIANN_PRELIMINARYANALYSIS - Preliminary analysis
    // What makes this "Preliminary Analysis":
    //   - Input: Individual MS files + predicted spectral library
    //   - Key flags: --quick-mass-acc (fast mass accuracy estimation), performance mode flags
    //   - NO --individual-mass-acc or --individual-windows (determined later from logs)
    //   - Output: *.quant files (preliminary quantification for each file)
    //   - Purpose: Generate data to automatically determine optimal mass accuracy and scan window settings
    // Note: mass_acc and scan_window are NOT set during preliminary analysis in quantms
    // when using automatic modes - they're determined from the preliminary results
    withName: 'DIANN_PRELIMINARYANALYSIS' {
        ext.args = [
            params.diann_debug ? "--verbose ${params.diann_debug}" : '',
            params.quick_mass_acc ? "--quick-mass-acc" : '',
            params.performance_mode ? "--min-corr 2 --corr-diff 1 --time-corr-only" : ''
        ].findAll { it != '' }.join(' ').trim()
    }

    // DIANN_ASSEMBLEEMPIRICALLIBRARY - Empirical library assembly
    // What makes this "Empirical Library Assembly":
    //   - Input: All MS files + predicted library + preliminary *.quant files
    //   - Key flags: --rt-profiling --gen-spec-lib
    //   - Uses --individual-mass-acc and --individual-windows (if automatic mode enabled)
    //   - Output: empirical_library.* (refined library based on actual data)
    //   - Purpose: Build experiment-specific library using preliminary results to improve identifications
    withName: 'DIANN_ASSEMBLEEMPIRICALLIBRARY' {
        ext.prefix = 'empirical_library'
        ext.args = [
            params.diann_debug ? "--verbose ${params.diann_debug}" : '',
            "--rt-profiling",
            "--gen-spec-lib",
            params.mass_acc_automatic ? "--individual-mass-acc" : '',
            params.scan_window_automatic ? "--individual-windows" : (params.scan_window ? "--window ${params.scan_window}" : '')
        ].findAll { it != '' }.join(' ').trim()
    }

    // DIANN_INDIVIDUALANALYSIS - Individual analysis
    // What makes this "Individual Analysis":
    //   - Input: Individual MS file + empirical library + FASTA
    //   - Key flags: --no-ifs-removal --no-main-report (suppress full reports, only generate .quant)
    //   - Uses refined mass accuracy settings from empirical library log (meta.mass_acc_ms1, meta.mass_acc_ms2, meta.scan_window)
    //   - Output: *.quant files (individual quantification for each file with refined library)
    //   - Purpose: Re-analyze each file individually with optimal settings before final aggregation
    withName: 'DIANN_INDIVIDUALANALYSIS' {
        ext.args = {
            [
                params.diann_debug ? "--verbose ${params.diann_debug}" : '',
                "--no-ifs-removal",
                "--no-main-report",
                "--relaxed-prot-inf",
                meta.pg_level ? "--pg-level ${meta.pg_level}" : '',
                meta.mass_acc_ms2 ? "--mass-acc ${meta.mass_acc_ms2}" : '',
                meta.mass_acc_ms1 ? "--mass-acc-ms1 ${meta.mass_acc_ms1}" : '',
                meta.scan_window ? "--window ${meta.scan_window}" : ''
            ].findAll { it != '' }.join(' ').trim()
        }
    }

    // DIANN_FINALQUANTIFICATION - Final quantification
    // What makes this "Final Quantification":
    //   - Input: All MS file names (basenames only) + empirical library + all individual *.quant files + FASTA
    //   - Key flags: --matrices (generate quantification matrices)
    //   - Outputs: diann_report.tsv, *.pr_matrix.tsv, *.pg_matrix.tsv (precursor and protein group quantification)
    //   - Uses --individual-windows if automatic mode (allows per-file scan window adjustments)
    //   - Purpose: Aggregate all individual analyses into final cross-run normalized quantification
    withName: 'DIANN_FINALQUANTIFICATION' {
        ext.prefix = 'diann_report'
        ext.args = [
            params.diann_debug ? "--verbose ${params.diann_debug}" : '',
            "--relaxed-prot-inf",
            params.pg_level != null ? "--pg-level ${params.pg_level}" : '',
            params.species_genes ? "--species-genes" : '',
            "--matrices",
            params.protein_level_fdr_cutoff != null ? "--qvalue ${params.protein_level_fdr_cutoff}" : '',
            params.diann_report_decoys ? "--report-decoys" : '',
            params.diann_export_xic ? "--xic" : '',
            params.scan_window_automatic ? "--individual-windows" : (params.scan_window ? "--window ${params.scan_window}" : '')
        ].findAll { it != '' }.join(' ').trim()
    }

    withName: 'QUANTMSUTILS_DIANN2MZTAB' {
        ext.args = {
            [
                params.max_precursor_charge ? "--charge ${params.max_precursor_charge}" : '',
                params.allowed_missed_cleavages != null ? "--missed_cleavages ${params.allowed_missed_cleavages}" : '',
                params.protein_level_fdr_cutoff != null ? "--qvalue_threshold ${params.protein_level_fdr_cutoff}" : '',
                params.enable_diann_mztab ? "--enable_diann2mztab" : '',
                meta.dia_params ? "--dia_params \"${meta.dia_params}\"" : ''
            ].findAll { it != '' }.join(' ').trim()
        }
    }
}
